<script lang="ts" setup>
import type { DataType } from './types';

import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';

import { Page } from '@vben/common-ui';

import { Button, message, Popconfirm, Space,Image } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deletePage, getPage ,translate} from '#/api/admin/translate';
import Icon from '#/components/Icons';
import { formatImagesList, queryStringToObject } from '#/utils';

defineOptions({
  name: 'PortalAdminPage',
});

const route = useRoute();
const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const viewTitle = routeMeta.title.replace('管理', '');
const code = ref('');
const translateLoadingMap = ref<Record<number, boolean>>({});

const gridOptions: VxeGridProps<DataType> = {
  rowConfig: {
    isCurrent: true,
    isHover: true,
  },
  columns: [
    { field: 'id', title: '编号' },
    { field: 'record_id', title: '翻译编号' },
    { field: 'table_name', title: '表' },
    { field: 'field_name', title: '字段'},
    {
        field: 'status',
        title: '状态',
        slots: {
            default: 'statusSlot',
        },
    },
    { field: 'old_value', title: '原始数据'},
    { field: 'field_value', title: '翻译数据'},
    {
      field: 'translate_time',
      title: '翻译时间',
      width: 100,
    },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: '操作',
 
    },
  ],

  keepSource: true,
  pagerConfig: {
    layouts: ['Total', 'Sizes', 'PrevPage', 'Number', 'NextPage', 'FullJump'], // 带总条数和每页大小选择
    pageSize: 20,
    pageSizes: [10, 20, 50, 100],
  },

  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const param = queryStringToObject(route.meta.param as string);
        if (param?.code) {
          formValues.code = param.code;
          code.value = param.code;
        }

        const { data } = await getPage({
          page: page.currentPage,
          limit: page.pageSize,
          ...formValues,
        });
        const total = data.list.length;
        data.total =data.total;
        data.list = formatImagesList(data.list, 'thumbnail');
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};
const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['code'],
      },
      fieldName: 'code',
      label: 'code',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: `请输入${viewTitle}`,
      },
      fieldName: 'keyword',
      label: `${viewTitle}名称:`,
    },
    {
    component: 'Select',
    componentProps: {
      placeholder: `请选择${viewTitle}状态`,
      options: [
        { label: '未翻译', value: 0 },
        { label: '已翻译', value: 1 },
      ]
    },
    fieldName: 'status',
    label: `${viewTitle}状态:`,
  },
    {
    component: 'Select',
    componentProps: {
      placeholder: `请选择${viewTitle}类型`,
      options: [
    { label: '导航', value: 'nav_menu' },
    { label: '新闻', value: 'news' },
    { label: '表单', value: 'form_concat' },
    { label: '产品属性', value: 'portal_module_attributes' },
    { label: '产品属性值', value: 'portal_module_attribute_values' },
    { label: '产品', value: 'portal_post' },
    { label: '车型特征', value: 'vechile_detail' },
    { label: '车型banner', value: 'vechile_banner' },
    { label: '车型', value: 'car_model' },
    { label:'产品分类',value:'portal_category'},
    { label: '产品参数', value: 'portal_post_attributes' },
    {label:'幻灯片',value:'slide_item'},
    {label:'促销中心',value:'promotion'},
    {label:'设置',value:'option'}
]
    },
    fieldName: 'table_name',
    label: `${viewTitle}类型:`,
  }
    
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  // 按下回车时是否提交表单
  submitOnEnter: true,
};
const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
  formOptions,
});

const handleDelete = async (row: DataType) => {
  const $table = GridApi.grid;
  if ($table) {
    const { msg } = await deletePage(row.id);
    $table.remove(row);
    message.success(msg);
  }
};

const openDialog = async (row?: DataType) => {
  const id = row?.id || 0;
  console.log(route)
  router.push({
    name: `AdmintranslateDetail`,
    params: { id },
  });
};

const translate_res = async (row: DataType) => {
  if (!row?.id) return;

  translateLoadingMap.value[row.id] = true; // 开始加载

  try {
    const { msg } = await translate({ id: row.id });
    message.success(msg || '翻译成功');
  } catch (e) {
    message.error('翻译失败');
  } finally {
    translateLoadingMap.value[row.id] = false; // 结束加载
  }
};

</script>

<template>
  <Page auto-content-height>
    <Grid :table-title="`${viewTitle}列表`">

       <template #thumbils="{ row }">
        <Image
          v-if="Array.isArray(row.thumbils) && row.thumbils.length > 0 && row.thumbils[0].url"
          :src="row.thumbils[0].url"
          :height="30"
          :width="30"
        />
      </template>

        <template #statusSlot="{ row }">
        <span>{{ row.status === 1 ? '已翻译' : '未翻译' }}</span>
        </template>
      <template #toolbar-tools>
        <Button class="mr-2" type="primary" @click="openDialog()">
          <span class="anticon">
            <Icon icon="ri:add-line" />
          </span>
          新增{{ viewTitle }}
        </Button>
      </template>

      <template #action="{ row }">
        <Space>
          <Button type="primary" @click="openDialog(row)">
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:file-edit-line" />
              </span>
            </template>
            编辑
          </Button>
          <Button type="primary" @click="translate_res(row)" :loading="translateLoadingMap[row.id]" :disabled="translateLoadingMap[row.id]">
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:file-edit-line" />
              </span>
            </template>
            翻译
          </Button>
          
          <Popconfirm
            cancel-text="否"
            ok-text="是"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <Button danger type="primary">
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:delete-bin-line" />
                </span>
              </template>
              删除
            </Button>
          </Popconfirm>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
